package com.wwk.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.wwk.constant.MessageConstant;
import com.wwk.constant.RedisConstant;
import com.wwk.entity.Result;
import com.wwk.pojo.Member;
import com.wwk.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @Classname MemberController会员登陆
 * @Description TODO
 * @Date 2020/11/10 18:31
 * @Created by com.wwk
 * @Author com.wwk
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    @RequestMapping("/login")
    public Result check(HttpServletResponse response, @RequestBody Map map){

        final String telephone = (String) map.get("telephone");
        String validateCode=(String) map.get("validateCode");
        //从redis中取出手机号对应的验证码，和输入的验证码进行匹配
        final String code = jedisPool.getResource().get(telephone + RedisConstant.SENDTYPE_LOGIN);

        if(code==null||validateCode==null||!code.equals(validateCode)){
            //验证失败
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }else{
            //验证成功
            //判断是否已经是会员了
            Member member = memberService.findByTelephone(telephone);
            if(member==null){
                //不是会员，则直接注册为会员
                member=new Member();
                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                memberService.add(member);
            }
            //用户添加后，然后将当前用户添加到客户端cookie中，用于跟踪用户
            Cookie cookie=new Cookie("login_member_telephone",telephone);
            /*  如果我们设置path，如果当前访问的路径包含了Cookie的路径（当前访问路径在Cookie路径基础上要比Cookie的范围小）
            Cookie就会加载request的对象之中。当前设置根路径，即所有路径都会访问这个cookie */
            cookie.setPath("/");//设置路径
            cookie.setMaxAge(60*60*30*24);//有效期30天
            response.addCookie(cookie);
            //保存会员信息到Redis中
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone, 60 * 30, json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }
    }
}
